package com.ccp.dev.workflow.controller;

import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.model.SysAuditModelType;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.system.dao.SysRoleDao;
import com.ccp.dev.system.model.*;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.system.model.SysRole;
import com.ccp.dev.system.service.SysUserService;
import com.ccp.dev.workflow.dao.TaskHistoryDao;
import com.ccp.dev.workflow.model.*;
import com.ccp.dev.workflow.model.bpm.ProcessTask;
import com.ccp.dev.workflow.service.BpmService;
import com.ccp.dev.workflow.service.FlowHandoverService;
import com.ccp.dev.workflow.service.ProcessRunService;
import com.ccp.dev.workflow.service.TaskReminderService;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * ClassDescribe:流程工作交接控制器
 * @author :jiayueqiao
 * Date: 2020-03-02
 * Since:1
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping(UrlConstants.PROJECT_ROOT + UrlConstants.PROJECT_MODULE_WORKFLOW + "/flowHandover")
@Action(ownermodel = SysAuditModelType.PROCESS_CENTER)
public class FlowHandoverController extends SysBaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(FlowHandoverController.class);

    @Resource
    private FlowHandoverService flowHandoverService;
    @Resource
    private SysRoleDao sysRoleDao;
    @Resource
    private TaskReminderService reminderService;
    @Resource
    private SysUserService sysUserService;

    /**
     * 我绑定的流程页面跳转
     * @return
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/bindFlow" )
    @Action(description = "我绑定的流程页面跳转",exectype = "页面跳转日志")
    public String bindFlow() {
        return getAutoView();
    }

    /**
     * 获取当前登录用户绑定的流程
     * @return
     */
    @RequestMapping( "/bindFlowByUser" )
    @Action(description = "我绑定的流程之通过当前用户获取",detail="当前用户绑定的流程数据查询<#if success>成功<#else>失败</#if>")
    @ResponseBody
    public ResultData bindFlowByUser(HttpServletRequest request) {
        //获取当前用户ID
        String userId = ContextUtil.getCurrentUserId();
        //获取查询条件
        QueryFilter queryFilter = new QueryFilter(request);
        //查询条件添加用户ID
        queryFilter.put("userId",userId);
        try {
            //通过userId查询绑定的流程
            List<FlowHandover> list = flowHandoverService.queryFlowByUserId(queryFilter);
            SysAuditThreadLocalHolder.putParamerter("success",true);
            return getResultDataSuccess("query.success",queryFilter.getPageBean().getTotalCount(),list);
        }catch (Exception e){
            LOGGER.error(e.getMessage());
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return getResultDataError("query.failure");
        }
    }

    /**
     * 获取当前登录用户角色绑定的流程
     * @return
     */
    @RequestMapping( "/bindFlowByRole" )
    @Action(description = "我绑定的流程之通过当前用户所属角色获取",detail="当前用户所属角色绑定的流程数据查询<#if success>成功<#else>失败</#if>")
    @ResponseBody
    public ResultData bindFlowByRule(HttpServletRequest request) {
        //获取当前用户角色ID
        String userId = ContextUtil.getCurrentUserId();
        List<SysRole> roleList = sysRoleDao.queryByUserId(userId);
        //获取查询条件
        QueryFilter queryFilter = new QueryFilter(request);
        //查询条件添加当前用户所属角色
        queryFilter.addFilter("roleList",roleList);
        try{
            //通过roleList查询角色绑定的流程
            List<FlowHandover> list = flowHandoverService.queryFlowByRoleIds(queryFilter);
            SysAuditThreadLocalHolder.putParamerter("success",true);
            return getResultDataSuccess("query.success",queryFilter.getPageBean().getTotalCount(),list);
        }catch (Exception e){
            LOGGER.error(e.getMessage());
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return getResultDataError("query.failure");
        }
    }

    /**
     * 获取当前登录用户组织绑定的流程
     * @return
     */
    @RequestMapping( "/bindFlowByOrg" )
    @Action(description = "我绑定的流程之通过当前用户所属组织获取",detail="当前用户所属组织绑定的流程数据查询<#if success>成功<#else>失败</#if>")
    @ResponseBody
    public ResultData bindFlowByOrg(HttpServletRequest request) {
        //获取当前用户的组织ID
        String orgId = ContextUtil.getCurrentOrgId();
        //获取查询条件
        QueryFilter queryFilter = new QueryFilter(request);
        //查询条件添加用户所属组织ID
        queryFilter.put("orgId",orgId);
        try{
            //通过orgId查询绑定的流程
            List<FlowHandover> list = flowHandoverService.queryFlowByOrgId(queryFilter);
            SysAuditThreadLocalHolder.putParamerter("success",true);
            return getResultDataSuccess("query.success",queryFilter.getPageBean().getTotalCount(),list);
        }catch (Exception e){
            LOGGER.error(e.getMessage());
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return getResultDataError("query.failure");
        }
    }

    //=======================正在审批的流程====================//

    /**
     * 代办事宜
     * @param model 视图模型对象
     * @return 页面路径
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/allPendingMatters")
    @Action(description = "正在审批的流程页面")
    public String pendingMattersView(Model model) {
        String warningSet = reminderService.getWaringSetJson();
        model.addAttribute("warningSet",warningSet);
        SysUser sysUser = (SysUser)ContextUtil.getCurrentUser();
        model.addAttribute("currentUserId",sysUser.getUserId());
        model.addAttribute("userPrivacyLevel",sysUser.getPrivacyLevel());
        return getAutoView();
    }

    /**
     * 所有待办任务列表
     * @param request request
     * @return Object
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST + "/allPendingMatters")
    @Action(description = "任务交接处查询所有待办任务数据列表",detail = "任务交接处查询所有待办任务数据列表<#if fl>成功<#else>失败</#if>")
    @ResponseBody
    public ResultData allPendingMatters(HttpServletRequest request) {
        QueryFilter queryFilter = new QueryFilter(request, true);
        queryFilter.addFilter("typeId", RequestUtil.getString(request,"typeId"));
        try{
            List<ProcessTask> list = flowHandoverService.queryAllTaskOnlyMe(queryFilter);
            SysAuditThreadLocalHolder.putParamerter("fl", true);
            return getResultDataSuccess("operation.success", queryFilter.getPageBean().getTotalCount(), list);
        }catch(Exception e){
            e.printStackTrace();
            SysAuditThreadLocalHolder.putParamerter("fl", false);
            return getResultDataError("operation.failure");
        }
    }

    /**
     * 交接
     * @param taskIds 任务id字符串，若是多个，则以逗号拼接
     * @return ResultData
     */
    @RequestMapping("/handoverWork")
    @Action(description = "交接任务",detail = "交接任务<#if fl>成功<#else>失败</#if>")
    @ResponseBody
    public ResultData handoverWork(@Param("taskIds") String taskIds,@Param("receiverId") String receiverId){
        try{
            SysUser receiver = sysUserService.getById(receiverId);
            if(BeanUtils.isEmpty(receiver)){
                return getResultDataError("receiver.is.not.exist");
            }
            //任务交接
            flowHandoverService.handoverWork(taskIds,receiver);
            SysAuditThreadLocalHolder.putParamerter("fl", true);
            return getResultDataSuccess("operation.success");
        }catch(Exception e){
            e.printStackTrace();
            SysAuditThreadLocalHolder.putParamerter("fl", false);
            return getResultDataError("operation.failure");
        }

    }
}
